// @ts-nocheck
import React, { useReducer, useCallback } from 'react';
import _ from 'lodash';
import { Affix, Button } from 'antd';
import { IndexProps } from './props-type';
import { StyleEdit, BillPreview, ContentConfig } from './pages';
import { getEditedBillJson, getEditedBillJsonForSpecial, getActionedBillJson, getCellChooseBillJson, isDividerRow, getKey, adjustCellWidth, adjustRowsWidth } from './common/help';
import { BASE_WIDTH } from './common/constant';
import './style/index.less';


const prefix = 'bill-templates';

const initialState = {
    cellSelectedId: '',
    cellSelectedRowId: '',
    cellSelectedBlockId: '',
    cellSelectedJson: {},
    rowSelectedJson: {},
    cellSelectedPageY: 0, // 当前选中编辑窗距页面顶部距离
    billJson: {},
    fileListLogo: [],
    fileListBottomPic: [],
    styleEditKey: getKey('styleEdit'),
    billPreviewKey: getKey('billPreview'),
    contentConfigKey: getKey('contentConfig'),
};
const reducer = (state, action) => {
    switch (action.type) {
        case 'setState':
            return { ...state, ...action.payload };
        default:
            throw new Error();
    }
};
const BillTemplates = ({
    type,
    brandId,
    billImageList,
    billName,
    templateJson,
    templateData,
    defaultBillJson,
    billJsonForm,
    brandList,
    styleEditOffTop,
    onBillSave,
    onBack,
    onUpdateStateSuper,
}: IndexProps) => {
    const [state, dispatch] = useReducer(reducer, { ...initialState, cellSelectedPageY: styleEditOffTop, billJson: billJsonForm });
    const {
        cellSelectedBlockId,
        cellSelectedRowId,
        cellSelectedId,
        cellSelectedJson,
        rowSelectedJson,
        billJson,
        styleEditKey,
        billPreviewKey,
        contentConfigKey,
        fileListLogo,
        fileListBottomPic,
    } = state;
    // 获取模板内容宽度
    const { width } = billJson;
    // 计算预览主容器宽度，向上取整，这里内容区宽度计算后，还得加上padding的值
    const computeWidth = width && typeof Number(width) === 'number' ? Number(width) : 48;
    const mainContainerWidth = Math.ceil(computeWidth * BASE_WIDTH / 48) + 24 * 2;
    const leftContentWidth = mainContainerWidth + 188;
    // styleEditProps
    const styleEditProps = {
        // 这里需要确定分割线状态
        isDivider: rowSelectedJson.row_type ? isDividerRow(cellSelectedBlockId, rowSelectedJson, billJson) : false,
        cellSelectedId,
        cellSelectedRowId,
        cellSelectedBlockId,
        cellSelectedJson,
        rowSelectedJson,
        billJson,
        // 选择字体大小、粗细、对齐方式的时候调用
        onEditCell(blockId, rowId, cellId, field) {
            // 需要调用一个方法，传入blockId, cellId, field，及billJson，最终返回新的billJson
            const cacheBillJson = getEditedBillJson(blockId, rowId, cellId, field, billJson);
            // 这里需要对当前
            dispatch({
                type: 'setState',
                payload: {
                    billJson: cacheBillJson,
                    // styleEditKey: getKey('styleEdit'),
                    cellSelectedJson: { ...cellSelectedJson, ...field },
                },
            });
        },
        // 插入空行、移除空行、增加分割线、移除分割线的时候调用, 这里action是具体的操作：addBlack、delBlack、addDivider、delDivider
        onEditBlankDivider(blockId, rowItem, action) {
            // 需要调用一个方法，传入blockId, cellId, field，及billJson，最终返回新的billJson
            const dataJson = getActionedBillJson(blockId, rowItem, action, billJson);
            dispatch({
                type: 'setState',
                payload: {
                    styleEditKey: getKey('styleEdit'),
                    billJson: dataJson.billJsonData,
                    rowSelectedJson: dataJson.cacheRowItemJson,
                },
            });
        },
    };
    // billPreviewProps
    const billPreviewProps = {
        type,
        billJson,
        cellSelectedId,
        templateData,
        billImageList,
        onSelectCell(e, cellItem, rowsItem, blockId) {
            dispatch({
                type: 'setState',
                payload: {
                    cellSelectedPageY: e.pageY - 150,
                    cellSelectedId: cellItem.cell_id,
                    cellSelectedJson: cellItem,
                    cellSelectedBlockId: blockId,
                    cellSelectedRowId: rowsItem.row_id,
                    rowSelectedJson: rowsItem,
                },
            });
        },
    };
    // contentConfigProps
    const contentConfigProps = {
        type,
        brandId,
        billName,
        brandList,
        fileListLogo,
        fileListBottomPic,
        billImageList,
        templateJson,
        billJson,
        onUpdateStateSuper,
        onChooseBillJson(action, blockJson, row_id, cell_id, blockIdList, rowIdList, cellIdList, parentRowIds) {
            // 请求选择cell的方法
            const cacheBillJson = getCellChooseBillJson(action, blockJson, row_id, cell_id, blockIdList, rowIdList, cellIdList, parentRowIds, billJson);
            // 这里需要对当前
            dispatch({
                type: 'setState',
                payload: {
                    billPreviewKey: getKey('billPreview'),
                    contentConfigKey: getKey('contentConfig'),
                    billJson: cacheBillJson,
                },
            });
        },
        // 修改state值
        onUpdateState(params) {
            dispatch({
                type: 'setState',
                payload: {
                    ...params,
                },
            });
        },
        // 上传图片
        onUploadImg(imgType, itemImg) {
            // 1、改变billJson
            const dataJson = getEditedBillJsonForSpecial(imgType, itemImg.imageId, billJson);
            dispatch({
                type: 'setState',
                payload: {
                    styleEditKey: getKey('styleEdit'),
                    billPreviewKey: getKey('billPreview'),
                    billJson: dataJson.billJsonData,
                },
            });
            // 2、改写billImageList
            const billImageListData = _.cloneDeep(billImageList);
            // 这里需要打标识，防止数组里不包含当前logo跟底部图片的情况
            let imgFlag = false;
            billImageListData.map(item => {
                // 如果当前项的imageId跟上面返回的一样，那么进行替换，说明是当前要改变的
                if (item.imageId === dataJson.oldDataValue) {
                    imgFlag = true;
                    item = itemImg;
                }
                return item;
            });
            // 如果没找到，那么push进入
            if (!imgFlag) {
                billImageListData.push(itemImg);
            }
            // 修改billImageList
            onUpdateStateSuper({ billImageList: billImageListData });
        },
        onChangeCellValue(typeCell, value) {
            // 2、改变billJson
            const dataJson = getEditedBillJsonForSpecial(typeCell, value, billJson);
            dispatch({
                type: 'setState',
                payload: {
                    styleEditKey: getKey('styleEdit'),
                    billPreviewKey: getKey('billPreview'),
                    billJson: dataJson.billJsonData,
                },
            });
        },
    };

    // 保存
    const handleSave = useCallback(() => {
        // 触发保存操作
        // 需要提交参数如下：
        onBillSave({
            templateStyle: JSON.stringify(billJson), // 模板json
        });
    }, [billJson, onBillSave]);

    // 恢复默认设置
    const handleRestore = useCallback(() => {
        // ====== 对返回的默认列表数据进行cell宽度动态处理======
        const cacheBillJson = _.cloneDeep(defaultBillJson);
        const billWidth = cacheBillJson.width;
        // 对block进行遍历
        cacheBillJson.block = cacheBillJson.block.map((itemBlock: any) => {
            itemBlock.rows = adjustRowsWidth(itemBlock.rows, billWidth);
            return itemBlock;
        });
        dispatch({
            type: 'setState',
            payload: {
                billJson: cacheBillJson,
            },
        });
    }, [defaultBillJson]);
    return (
        <div className={prefix}>
            <div className="container-set">
                <div className="left-content" style={{ width: leftContentWidth }}>
                    <div className="title"><h3>{`${billJson.name}模板预览`}</h3></div>
                    <div className="content">
                        {/* @ts-ignore */}
                        <StyleEdit {...styleEditProps} key={styleEditKey} />
                        <BillPreview {...billPreviewProps} key={billPreviewKey} />
                    </div>
                </div>
                {/* @ts-ignore */}
                <ContentConfig {...contentConfigProps} key={contentConfigKey} />
            </div>
            {/* 操作按钮区 */}
            <Affix offsetBottom={50}>
                <div className="form-action">
                    {/* eslint-disable-next-line react/jsx-no-bind */}
                    <Button type="primary" onClick={() => handleSave()}>保存</Button>
                    {/* eslint-disable-next-line react/jsx-no-bind */}
                    <Button onClick={() => handleRestore()}>恢复默认设置</Button>
                    {/* eslint-disable-next-line react/jsx-no-bind */}
                    <Button onClick={() => onBack()}>返回</Button>
                </div>
            </Affix>
        </div>
    );
};
// 抛出相关组件, 方法
export { BillPreview, adjustCellWidth };
export default BillTemplates;
